/*
 * Copyright (c) 2019 - 2020 IoT Company of Midea Group.
 *
 * File Name 	    : mcntl_cjson.c
 * Description	    :
 *
 * Version	        : v0.0.1
 * Author			: yexb
 * Date	            : 2021/09/28  msmart4.0
 * History	        :
 */

#include "mcntl_cjson.h"

// #define MCNTL_CJSON_RECURSIVE_DEBUG

/* Calculate a cjson structure mem consumption */
MS_LAYER_EXPORT unsigned int mcntl_cjson_calculate_size(mcntl_cjson* item)
{
    unsigned int size = 0, child_size = 0;
    mcntl_cjson* next = NULL;

    while (item != NULL) {
#ifdef MCNTL_CJSON_RECURSIVE_DEBUG
        MS_LOGI("Find item node : %s", item->string);
#endif
        size += sizeof(mcntl_cjson);
        next = item->next;
        if (!(item->type & cJSON_IsReference) && (item->child != NULL)) {
            child_size = mcntl_cjson_calculate_size(item->child);
#ifdef MCNTL_CJSON_RECURSIVE_DEBUG
            MS_LOGI("Find child item of: %s , len : %d", item->string, child_size);
#endif
            size += child_size;
        }
        if (!(item->type & cJSON_IsReference) && (item->valuestring != NULL)) {
            size += (strlen(item->valuestring) + sizeof(""));
#ifdef MCNTL_CJSON_RECURSIVE_DEBUG
            MS_LOGI("Find item string : %s ,len : %d", item->valuestring, strlen(item->valuestring) + sizeof(""));
#endif
        }
        if (!(item->type & cJSON_StringIsConst) && (item->string != NULL)) {
            size += (strlen(item->string) + sizeof(""));
#ifdef MCNTL_CJSON_RECURSIVE_DEBUG
            MS_LOGI("Find item string : %s ,len : %d", item->string, strlen(item->string) + sizeof(""));
#endif
        }
        item = next;
    }
    return size;
}

MS_LAYER_EXPORT mcntl_cjson* mcntl_cjson_get_object_item_recursive(mcntl_cjson* item, const char* name)
{
    mcntl_cjson* next = NULL;
    mcntl_cjson* result = NULL;

    while (item != NULL) {
#ifdef MCNTL_CJSON_RECURSIVE_DEBUG
        MS_LOGI("Find item node : %s", item->string);
#endif
        next = item->next;
        if (item->child != NULL) {
#ifdef MCNTL_CJSON_RECURSIVE_DEBUG
            MS_LOGI("Find child item of: %s", item->string);
#endif
            result = mcntl_cjson_get_object_item_recursive(item->child, name);
            if (result != NULL) {
                return result;
            }
        }
        if (item->string != NULL) {
            if (0 == strcmp(item->string, name)) {
                return item;
            }
        }
        item = next;
    }
    return NULL;
}

MS_LAYER_EXPORT char* mcntl_cjson_get_string_value(const mcntl_cjson* const item)
{
    if (!cJSON_IsString(item)) {
        return NULL;
    }

    return item->valuestring;
}

MS_LAYER_EXPORT double mcntl_cjson_get_number_value(const mcntl_cjson* const item)
{
    if (!cJSON_IsNumber(item)) {
        return (double)0;
    }

    return item->valuedouble;
}

MS_LAYER_EXPORT bool mcntl_cjson_get_bool_value(const mcntl_cjson* const item)
{
    if (cJSON_IsTrue(item)) {
        return true;
    } else {
        return false;
    }
}
